#include "MotionTrigger.h"

MotionTrigger::MotionTrigger(int sample_long,int wert_zahl,ssi_real_t left,
							 ssi_real_t right,
							 ssi_real_t up,
							 ssi_real_t bottom):
Trigger (0, 2),
_trigger_on (false),_time_long(sample_long),_wert_zahl(wert_zahl),
_left (left), _right (right), _up (up), _bottom (bottom){

}

MotionTrigger::~MotionTrigger(void){ }

void MotionTrigger::consume (SSI_Consumer::info consume_info,
			  ssi_size_t stream_in_num,
			  ssi_stream stream_in[]){
				  ssi_real_t *dataptr = ssi_pcast (ssi_real_t, stream_in[0].ptr);
				  ssi_real_t x,y,vx,vy,ex,ey;
				  vx=ex=0;
				  vy=ey=0;
				  if(_wert_zahl!=0) {ssi_real_t *wert_list = new ssi_real_t[_wert_zahl];}
				  memcpy();
				  if(_)		
				  for (ssi_size_t i = 0; i < stream_in[0].num; i++) {
					   
					  x = *dataptr++;
					  y = *dataptr++;
					  if (i == 0 ){ex=x;ey=y; }
					  bool in_region = _left <= x && x <= _right && _up <= y && y <= _bottom;
					  bool begin_trigger = (x!=vx && y!=vy )||(x==vx && y!=vy )||(x!=vx && y==vy );
					  bool end_trigger  = x==vx && y==vy && vx==ex && vy== ey;
					  
					  if (!_trigger_on && in_region && begin_trigger && !end_trigger) {
						  _trigger_start = consume_info.time + i / stream_in[0].sr;
						  _trigger_on = true;
					  }
					  else if (_trigger_on && in_region && end_trigger ) {
						  _trigger_stop = consume_info.time + i / stream_in[0].sr;
						  update (_trigger_start, _trigger_stop-_trigger_start, SSI_Consumer::COMPLETED); 
						  _trigger_on = false;
					  }else if (_trigger_on && !in_region ) {
						  _trigger_stop = consume_info.time + i / stream_in[0].sr;
						  update (_trigger_start, _trigger_stop-_trigger_start, SSI_Consumer::COMPLETED); 
						  _trigger_on = false;
					  }

					  vx = x; 
					  vy = y;

				  }
}